package com.kldy8.kldyw.logre;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.kldy8.kldyw.Constant;
import com.kldy8.kldyw.R;
import com.kldy8.kldyw.logre.LoginActivity;
import com.kldy8.kldyw.system.ServerApi;
import com.kldy8.kldyw.system.ServerCallBack;
import com.kldy8.kldyw.tools.TextUtil;

import org.json.JSONException;
import org.json.JSONObject;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.utils.SMSLog;
import okhttp3.Request;

import static com.mob.tools.utils.R.getStringRes;

/**
 *   注册
 * @author 钟震华
 * create at 2016/3/22 21:05
 */
public class ForgetpwdActivity extends AppCompatActivity implements View.OnClickListener{

    // UI references.
    private AutoCompleteTextView mPhoneView;
    private EditText mPasswordView;
    private EditText mVerifyView;
    private View mProgressView;
    private View mRegisterView;
    private ActionBar actionBar ;
    private Button forget_btn;
    private Button verification_btn;

    private String mphone;
    private String verification;
    private String password;
//    private TextView user_accept_tv;
    Handler timeHandler = new Handler();
    private int count = 60;//倒计时
    private boolean check = true;
    private static InputMethodManager mInputMethodManager;
    private EventHandler handler;
    private EventHandler thehandler;

    private TimeCount time;

    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_forget_pwd);
        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        init();
        smsCallback();
    }
    /**
     * 注册
     *
     * @throws
     */
    private void forgetPwd(String phone,String password ) throws Exception {}


    private void smsCallback() {
        handler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    Log.e("", "回调完成");
                } else {
                    ((Throwable) data).printStackTrace();
                }
            }
        };

        thehandler = new EventHandler() {
            public void afterEvent(int event, int result, Object data) {
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    /** 提交验证码 */
                    afterSubmit(result, data);
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    /** 获取验证码成功后的执行动作 */
                    Log.e("", " 获取验证码成功后的执行动作 ");
                    afterGet(result, data);
                }
            }
        };
        SMSSDK.registerEventHandler(handler);
        SMSSDK.registerEventHandler(thehandler);// 注册短信回调
    }


    private void init() {
        SMSSDK.initSDK(this, Constant.APP_KEY,  Constant.APP_SECRET);
        actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        mRegisterView=findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
        mPhoneView= (AutoCompleteTextView) findViewById(R.id.phone_forget_edt);
        mVerifyView= (EditText) findViewById(R.id.verification_edt);
        mPasswordView= (EditText) findViewById(R.id.password_forget_edt);
//        user_accept_tv= (TextView) findViewById(R.id.user_accept_tv);
        forget_btn=(Button)findViewById(R.id.forget_btn);
        verification_btn=(Button)findViewById(R.id.verification_btn);

        verification_btn.setOnClickListener(this);
        forget_btn.setOnClickListener(this);
//        user_accept_tv.setOnClickListener(this);

        time = new TimeCount(verification_btn,60000, 1000);//构造CountDownTimer对象

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        int id = item.getItemId();
        if (id == android.R.id.home)
        {
            this.finish();
        }
//        if (id == R.id.action_register)
//        {
//            return true;
//        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed()
    {
        super.onBackPressed();
    }
    public void onClick(View v){
        switch (v.getId()){
            case R.id.forget_btn:
                confirm_next();
                showProgress(true);
                break;
            case R.id.verification_btn:
                if(check)
                {
                    getCode();
                }
                break;
            case R.id.user_accept_tv:
                Intent intent=new Intent();
                this.startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void confirm_next() {
        mPhoneView.setError(null);
        mVerifyView.setError(null);
        mPasswordView.setError(null);
        mphone=mPhoneView.getText().toString();
        verification=mVerifyView.getText().toString();
        password=mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        if (TextUtils.isEmpty(password) || !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
            showProgress(false);

        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(mphone)) {
            mPhoneView.setError(getString(R.string.error_field_required));
            focusView = mPhoneView;
            cancel = true;
            showProgress(false);

        }else if (TextUtil.isEmpty(verification)) {
            mVerifyView.setError(getString(R.string.error_ver_required));
            focusView = mVerifyView;
            cancel = true;
            showProgress(false);

        }else if (!TextUtil.isMobileNumber(mphone)) {
            mPhoneView.setError(getString(R.string.error_invalid_email));
            focusView = mPhoneView;
            cancel = true;
            showProgress(false);

        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
            showProgress(false);
        }
        else
        {
//            SMSSDK.submitVerificationCode("86", mphone, verification);
            ServerApi.initpassword(mphone, password, verification, new ServerCallBack()
            {
                @Override
                public void onError(Request request, Exception e)
                {
                    showProgress(false);
                    Log.e("onError",e.getMessage());
                    Toast.makeText(ForgetpwdActivity.this,"网络错误，请稍后重试",Toast.LENGTH_LONG).show();

                }

                @Override
                public void onResponse(String response) throws JSONException
                {
                    Log.e("response",response);
                    showProgress(false);

                    JSONObject object = new JSONObject(response);
                    if ("0".equals(object.optString("code")))
                    {
                        Toast.makeText(ForgetpwdActivity.this,"修改成",Toast.LENGTH_LONG).show();
                        finish();
                    }
                    else if ("10002".equals(object.optString("code")))
                    {
                        Toast.makeText(ForgetpwdActivity.this,"此手机号码没有注册",Toast.LENGTH_LONG).show();
                    }
                    else if ("10006".equals(object.optString("code")))
                    {
                        Toast.makeText(ForgetpwdActivity.this,"验证码错误",Toast.LENGTH_LONG).show();
                    }
                    else if ("10007".equals(object.optString("code")))
                    {
                        Toast.makeText(ForgetpwdActivity.this,"用户名已存在",Toast.LENGTH_LONG).show();
                    }
                    else if ("10008".equals(object.optString("code")))
                    {
                        Toast.makeText(ForgetpwdActivity.this,"用户类型非法",Toast.LENGTH_LONG).show();
                    }
                    else if ("10009".equals(object.optString("code")))
                    {
                        Toast.makeText(ForgetpwdActivity.this,"电话号码格式错误",Toast.LENGTH_LONG).show();
                    }
                    else if ("10010".equals(object.optString("code")))
                    {
                        Toast.makeText(ForgetpwdActivity.this,"电话号码已有绑定的账号",Toast.LENGTH_LONG).show();
                    }
                    else if ("10011".equals(object.optString("code")))
                    {
                        Toast.makeText(ForgetpwdActivity.this,"密码格式不合法",Toast.LENGTH_LONG).show();
                    }
                    else
                    {
                        Toast.makeText(ForgetpwdActivity.this,"系统错误，请稍后重试",Toast.LENGTH_LONG).show();
                    }
                }
            });
        }
    }

    /**
     * 验证密码长度
     * @param password
     * @return
     */
    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 4;
    }

    private void startNext() {
        Intent intent = new Intent(ForgetpwdActivity.this,
                LoginActivity.class);
        startActivity(intent);
        finish();
    }

    //获取验证码
    private void getCode()
    {
        mVerifyView.setError(null);
        mphone=mPhoneView.getText().toString();
        if(TextUtil.isEmpty(mphone)) {
            mPhoneView.setError(getString(R.string.isphone_null_toast));
            return;
        }
        if(!TextUtil.isMobileNumber(mphone)) {
            mPhoneView.setError(getString(R.string.isphone_not_toast));
            return;
        }
//        SMSSDK.getVerificationCode("86", mphone);
        time.start();
        ServerApi.SMS(mphone,ServerApi.SMS_TYPE_INITPASSWORD ,new ServerCallBack()
        {
            @Override
            public void onError(Request request, Exception e)
            {
                Log.e("response",e.getMessage());
                Toast.makeText(ForgetpwdActivity.this,"网络错误，请稍后重试",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResponse(String response) throws JSONException
            {
                Log.e("response",response.toString());
                JSONObject object = new JSONObject(response);
                if ("0".equals(object.optString("code")))
                {
                    Toast.makeText(ForgetpwdActivity.this,"发送成功，请查看手机验证码",Toast.LENGTH_LONG).show();
                }
                else if ("10002".equals(object.optString("code")))
                {
                    Toast.makeText(ForgetpwdActivity.this,"此手机号码没有注册",Toast.LENGTH_LONG).show();
                }
                else
                {
                    Toast.makeText(ForgetpwdActivity.this,"系统错误，请稍后重试",Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    /**
     * 重新获取验证码倒计时
     * */
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            count--;
            if (count > 0) {
                verification_btn.setText("重新获取(" + count + ")");
                verification_btn.setClickable(false);
                verification_btn.setTextSize(15);
                timeHandler.postDelayed(this, 1000);

            } else if (count == 0) {
                count = 60;
                check = true;
                verification_btn.setText("重新获取");
                verification_btn.setClickable(true);
                timeHandler.removeCallbacks(runnable, 1000);
            }
        }

    };

    /**
     * 获取验证码成功后执行的动作
     *
     * @param result
     * @param data
     */
    private void afterGet(final int result, final Object data) {
        runOnUiThread(new Runnable() {
            public void run() {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    check = false;
                    timeHandler.postDelayed(runnable, 1000);
                    Toast.makeText(ForgetpwdActivity.this, "已将验证码发送到该手机！",
                            Toast.LENGTH_SHORT).show();
                } else {
                    ((Throwable) data).printStackTrace();
                    Throwable throwable = (Throwable) data;
                    // 根据服务器返回的网络错误，给toast提示
                    try {
                        JSONObject object = new JSONObject(
                                throwable.getMessage());
                        String des = object.optString("detail");
                        if (!TextUtils.isEmpty(des)) {
                            Toast.makeText(ForgetpwdActivity.this, des,
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } catch (JSONException e) {
                        SMSLog.getInstance().w(e);
                    }
                    // / 如果木有找到资源，默认提示
                    int resId = getStringRes(ForgetpwdActivity.this,
                            "smssdk_network_error");
                    if (resId > 0) {
                        Toast.makeText(ForgetpwdActivity.this, resId,
                                Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    protected void onDestroy() {
        SMSSDK.unregisterAllEventHandler();
        super.onDestroy();

    }
    /**
     * TODO 跳转dialog
     */
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mRegisterView.setVisibility(show ? View.GONE : View.VISIBLE);
            mRegisterView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mRegisterView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }
    /**
     * 验证码正确 进行页面跳转
     *
     * @param result
     * @param data
     */
    private void afterSubmit(final int result, final Object data) {
        runOnUiThread(new Runnable() {
            public void run() {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    Log.e("", "验证码正确");
                    count = 60;
                    check = true;
                    verification_btn.setText("重新获取");
                    timeHandler.removeCallbacks(runnable);
                    showProgress(true);
                    try {
                        forgetPwd(mPhoneView.getText().toString(),
                                mPasswordView.getText().toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    mVerifyView.setError(null);
                    ((Throwable) data).printStackTrace();
                    mVerifyView.setError("验证码错误");
                }
            }
        });
    }
    // 隐藏软件盘
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {

            if (ForgetpwdActivity.this.getCurrentFocus() != null
                    && ForgetpwdActivity.this.getCurrentFocus().getWindowToken() != null) {
                mInputMethodManager.hideSoftInputFromWindow(ForgetpwdActivity.this
                                .getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }

}
